package com.JingYan.util.file;

import com.JingYan.exception.CustomException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

public class DownloadUtils {
    private static final Logger logger = LoggerFactory.getLogger(DownloadUtils.class);
    /**
     * 文件的内容类型
     */
    private static String getFileContentType(String name){
        String result = "";
        String fileType = name.toLowerCase();
        if (fileType.endsWith(".png")) {
            result = MimeTypeUtils.IMAGE_PNG;
        } else if (fileType.endsWith(".gif")) {
            result = MimeTypeUtils.IMAGE_GIF;
        } else if (fileType.endsWith(".jpg") || fileType.endsWith(".jpeg")) {
            result = MimeTypeUtils.IMAGE_JPEG;
        } else if(fileType.endsWith(".svg")){
            result = MimeTypeUtils.IMAGE_SVG_XML;
        } else if (fileType.endsWith(".doc")) {
            result = MimeTypeUtils.APPLICATION_MSWORD;
        } else if (fileType.endsWith(".xls")) {
            result = MimeTypeUtils.APPLICATION_X_EXCEL;
        } else if (fileType.endsWith(".zip")) {
            result = MimeTypeUtils.APPLICATION_ZIP;
        } else if (fileType.endsWith(".pdf")) {
            result = MimeTypeUtils.APPLICATION_PDF;
        }else {
            result = MimeTypeUtils.APPLICATION_OCTET_STREAM;
        }
        return result;
    }

    /**
     * 下载文件
     * @param path 文件的位置
     * @param fileName 自定义下载文件的名称
     * @param resp http响应
     * @param req http请求
     */
    public static void downloadFile(String path, String fileName, HttpServletResponse resp, HttpServletRequest req){
        // 字符编码格式
        String charsetCode = "utf-8";
        File file = new File(path);
        InputStream is = null;
        OutputStream os = null;
        try {
            /**
             * 中文乱码解决
             */
            String type = req.getHeader("User-Agent").toLowerCase();
            fileName = URLEncoder.encode(fileName, charsetCode);
            // 设置响应的头部信息
            resp.setHeader("content-disposition", "attachment;filename=" + fileName);
            // 设置响应内容的类型
            resp.setContentType(getFileContentType(fileName));
            // 设置响应内容的长度
            resp.setContentLength((int) file.length());
            // 输出
            is= new FileInputStream(file);
            os=resp.getOutputStream();
            byte[] buffer = new byte[10240];
            int length = -1;
            while ((length = is.read(buffer)) != -1) {
                os.write(buffer, 0, length);
                os.flush();
            }
        } catch (Exception e) {
            logger.error("执行downloadFile发生了异常：" + e.getMessage());
            throw new CustomException("执行downloadFile发生了异常：" + e.getMessage());
        }finally {
            try {
                os.close();
            } catch (IOException e) {
            }
            try {
                is.close();
            } catch (IOException e) {
            }
        }
    }

}
